package com.test;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class ImageDownloader {
	private HashMap<String, SoftReference<Drawable>> imageCache;
	
	public ImageDownloader() {
		imageCache = new HashMap<String, SoftReference<Drawable>>();
	}
	
	public static Drawable loadImageFromUrl(String url) {
		Bitmap bm = null;
		try {
			URLConnection conn = (new URL(url)).openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		BitmapDrawable a = new BitmapDrawable(bm);
		return a.mutate();
	}
	
	public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> sr = imageCache.get(imageUrl);
			Drawable d = sr.get();
			if (d != null)
				return d;
		}
		
		final Handler handler = new Handler() {
			public void handleMessage(Message m) {
				imageCallback.imageLoaded((Drawable) m.obj, imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Drawable d = loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(d));
				Message m = handler.obtainMessage(0, d);
				handler.sendMessage(m);
			}
		}.start();
		
		return null;
	}
}
